package co.edu.usbcali.pqr.dataaccess.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import co.edu.usbcali.pqr.dataaccess.api.HibernateDaoImpl;
import co.edu.usbcali.pqr.modelo.AreasInvolucradas;
import co.edu.usbcali.pqr.modelo.dto.ConsultaSolicitudDTO;


@Scope("singleton")
@Repository("AreasInvolucradasDAO")
public class AreasInvolucradasDAO extends HibernateDaoImpl<AreasInvolucradas, Long>
    implements IAreasInvolucradasDAO {

	private static final Logger log = LoggerFactory.getLogger(AreasInvolucradasDAO.class);
    @Resource
    private SessionFactory sessionFactory;

    public static IAreasInvolucradasDAO getFromApplicationContext(
        ApplicationContext ctx) {
        return (IAreasInvolucradasDAO) ctx.getBean("AreasInvolucradasDAO");
    }
    
    @SuppressWarnings("unchecked")
   	@Override
   	public Long existeNombreArea(String pDescripcion) throws Exception {
   		Long cant = 0L;
   			try {
   			Query query = getSession().getNamedQuery("existe_nombre_area_involucrada");
   			query.setParameter("pDescripcion", pDescripcion);
   			List<Long> lista = query.list();

   			if (lista!=null) {
   				cant =lista.get(0);
   			}
   			
   		} catch (Exception e) {
   			log.error(e.getMessage());
   			throw e;
   		}
   		return cant;

   	}

	@SuppressWarnings("unchecked")
	@Override
	public Long consultarIdAreaXLoginUsuario(String login) throws Exception {
   		Long idArea = 0L;
			try {
			Query query = getSession().getNamedQuery("consultar_idArea_XLoginUsuario");
			query.setParameter("pLogin", login);
			List<Long> lista = query.list();

			if (lista!=null) {
				idArea =lista.get(0);
			}
			
		} catch (Exception e) {
			log.error(e.getMessage());
			throw e;
		}
		return idArea;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ConsultaSolicitudDTO> consultarSolicitudesXArea(Long idArea) throws Exception {

		List<ConsultaSolicitudDTO> list = null;
		
		try {
			
			Query query = getSession().getNamedQuery("consultar_solicitudes_x_id_area");
			query.setParameter("pIdArea", idArea);
			query.setResultTransformer(Transformers.aliasToBean(ConsultaSolicitudDTO.class));
			list = query.list();
			
		} catch (Exception e) {
			throw e;
		}
		
		return list;
	}
	
}
